var config = require("../../config.js")
var util = require("../../utils/MD5.js")
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopInfo: {}, // 店铺信息
    srInfo: {}, // 收入信息
    srScale: 0, //收入比例
    filePath: config.FilePath,
    C_SHOP_NO: "",
    loadtext: "",
    downClass: true,
    canvasY: 25,
    dataArr: [],
    amountArr: [1536, 5345, 3215, 5485, 3154, 5467, 9834],
    pageindex: 1,
    pagesize: 10,
    customList: [],
    qsData: [], // 趋势
    width: 0,
    msgCount: 0,
    shopList: [],
    chooseShopName: "",
    chooseIndex: 0,
    showChoose: false,
    isMain: true, // 是否是总店

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;


    wx.getSystemInfo({
      success: res => {
        var w = (res.screenWidth - 20) / 3 * 0.7;
        this.setData({
          width: w,
        })
      },
    })

    this.scaleTime();
    // this.createCanvasData();
    this.selectHasFaceFunction();
  },

  viewBB() {
    wx.navigateTo({
      url: '/pages/web/web',
    })
  },

  viewBBxf() {
    wx.navigateTo({
      url: '/pages/web2/web2',
    })
  },

  getMessageList() {
    var str = "ShopNo=" + this.data.C_SHOP_NO;
    var md5 = util.md5(str);
    var data = {
      bNo: 2000,
      ShopNo: this.data.C_SHOP_NO,
      MD5: md5.toUpperCase()
    }
    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        if (res.data.code === "100") {
          // 1未读 2已读 3删除 N_MsgState 
          var count = 0;
          for (var i = 0; i < res.data.msgList.length; i++) {
            if (res.data.msgList[i].N_MsgState == 1) {
              count++;
            }
          }
          this.setData({
            msgCount: count
          })
        }
      }
    })
  },

  getShopData() {
    var str = "ShopNo=" + this.data.C_SHOP_NO,
      md5 = util.md5(str),
      _this = this,
      data = {
        bNo: 1751,
        ShopNo: this.data.C_SHOP_NO,
        MD5: md5.toUpperCase()
      };
    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        var data = JSON.parse(res.data.replace(/\(|\)/g, ""));
        var data2 = JSON.parse(data.Result);
        if (data.code === "100") {
          for (var i = 0; i < data2.length; i++) {
            data2[i].Sy = parseFloat(data2[i].Sy)
            // data2[i].Sy = this.data.amountArr[i]
            // data2[i].Sy = parseInt(Math.random() * 10000);
            data2[i].Time = data2[i].Time.replace("2018-", "")
          }
          _this.setData({
            qsData: data2,
          })
          if (data2.zrtb < 0) {
            _this.setData({
              downClass: false
            })
          }
          this.createCanvasData();
        }
      }
    })
  },

  /**
   * 查询是否有人脸权限
   */
  selectHasFaceFunction() {
    var str = "ShopNo=" + config.SHOP_NO;
    var md5 = util.md5(str);
    var data = {
      bNo: 1712,
      ShopNo: config.SHOP_NO,
      MD5: md5.toUpperCase()
    };

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {

      }
    })
  },

  /**
   * 创建报表canvas
   */
  createCanvasData() {
    wx.getSystemInfo({
      success: res => {
        var w = res.windowWidth;
        var h = res.windowHeight
        var dis = (w - 30) / 6.3;
        var c = wx.createCanvasContext("myCanvas");
        var big = this.data.qsData[0].Sy;
        var small = this.data.qsData[0].Sy;
        for (var i = 1; i < this.data.qsData.length; i++) {
          if (this.data.qsData[i]) {
            if (this.data.qsData[i].Sy > big) {
              big = this.data.qsData[i].Sy;
            }
            if (this.data.qsData[i].Sy < small) {
              small = this.data.qsData[i].Sy;
            }
          }
        }
        var average = parseInt((big + small) / 2);
        if (average != 0) {
          var f = 0;
          if (this.data.qsData[0].Sy > 5) {
            if (this.data.qsData[0].Sy < average) {
              f = parseInt(((average - this.data.qsData[0].Sy) * 90) / average + 100)
            } else {
              f = parseInt(100 - ((this.data.qsData[0].Sy - average) * 90) / average)
            };
          } else {
            f = 180;
          }
          var e = 10;
          var e2 = 10;
          var y = 180;
          // 绘制y轴
          c.beginPath();
          c.setFontSize(10);
          c.moveTo(e, 0);
          c.lineTo(e, y);
          c.stroke();
          c.closePath();

          c.beginPath();
          c.moveTo(e, y);
          c.lineTo(600, y);
          c.stroke();
          c.closePath();

          c.beginPath();
          c.setStrokeStyle("#dddddd")
          c.moveTo(e, y * 0.25);
          c.setFillStyle("#999999")
          c.lineTo(600, y * 0.25);
          var y4 = average + "";
          c.fillText(parseInt(average + average * 0.5), w - (y4.length - 1) * 10, y * 0.25);
          c.stroke();
          c.closePath();

          c.beginPath();
          c.setStrokeStyle("#dddddd")
          c.moveTo(e, y / 2);
          c.setFillStyle("#999999")
          c.lineTo(600, y / 2);
          var y4 = average + "";
          c.fillText(average, w - (y4.length - 1) * 10, y / 2);
          c.stroke();
          c.closePath();

          c.beginPath();
          c.setStrokeStyle("#dddddd")
          c.moveTo(e, y * 0.75);
          c.setFillStyle("#999999")
          c.lineTo(600, y * 0.75);
          var y4 = average + "";
          c.fillText(parseInt(average * 0.5), w - (y4.length - 1) * 10, y * 0.75);
          c.stroke();
          c.closePath();

          var yArr = [];
          var k = 0;
          var d = 0;
          for (var i = 1; i < this.data.qsData.length; i++) {
            k += parseInt(dis - 0.8);
            d += parseInt(dis - 2);
            if (this.data.qsData[i].Sy > 1) {
              if (this.data.qsData[i].Sy < average) {
                yArr.push({
                  x: k,
                  x2: d,
                  y: parseInt(((average - this.data.qsData[i].Sy) * 90) / average + 90)
                })
              } else {
                yArr.push({
                  x: k,
                  x2: d,
                  y: parseInt(100 - ((this.data.qsData[i].Sy - average) * 90) / average)
                });
              }
            } else {
              yArr.push({
                x: k,
                x2: d,
                y: 180
              })
            }
          };

          // 绘制趋势线
          c.setLineWidth = 1;
          c.setStrokeStyle("#df9835");
          c.beginPath();
          c.moveTo(e, f);
          c.arc(e, f, 2, 0, 2 * Math.PI, false);

          var y2 = 0;
          var y3 = 0;
          c.fillText(this.data.qsData[0].Sy, e + 5, f + 5);
          c.fillText(this.data.qsData[0].Time, e, y + 15);
          for (var i = 1; i <= this.data.qsData.length - 1; i++) {

            // y2 = y - parseInt((90 / average) * this.data.qsData[i].Sy)
            // debugger
            y3 = yArr[i - 1].y + 5;
            c.lineTo(yArr[i - 1].x, yArr[i - 1].y);
            c.fillText(this.data.qsData[i].Sy, yArr[i - 1].x + 5, y3);
            c.fillText(this.data.qsData[i].Time, yArr[i - 1].x2, y + 15);
          }
          c.stroke();
          c.closePath();

          for (var i = 0; i < yArr.length; i++) {
            c.beginPath();
            c.arc(yArr[i].x, yArr[i].y, 2, 0, 2 * Math.PI, false);
            c.fill();
            c.stroke();
            c.closePath();
          }

        } else {
          var e = 20;
          var e2 = 20;

          var xArr = [];
          for (var i = 1; i < this.data.qsData.length; i++) {
            e += (dis - 0.8);
            e2 += dis - 3;
            xArr.push({
              x1: e,
              x2: e2
            })
          }
          c.beginPath();
          c.setLineWidth = 1;
          c.setFontSize(10);
          c.setStrokeStyle("#df9835");
          c.moveTo(20, 90);
          c.arc(20, 90, 2, 0, 2 * Math.PI, false);
          for (var i = 0; i < xArr.length; i++) {
            c.lineTo(xArr[i].x1, 90);
            c.fillText(this.data.qsData[i].Sy, xArr[i].x1 - 3, 85);
            c.fillText(this.data.qsData[i].Time, xArr[i].x2 - 4, 180);
          }
          c.fillText(this.data.qsData[0].Sy, 17, 85);
          c.fillText(this.data.qsData[0].Time, 10, 180);
          c.stroke();
          c.closePath();

          for (var i = 0; i < xArr.length; i++) {
            c.beginPath();
            c.setFillStyle("#df9835")
            c.arc(xArr[i].x1, 90, 2, 0, 2 * Math.PI, false);
            c.stroke();
            c.fill();
            c.closePath();
          }
        }

        wx.drawCanvas({
          //画布标识，传入<canvas/>的cavas-id
          canvasId: 'myCanvas',
          //获取绘制行为， 就相当于你想做到菜context.getActions()就是食材
          actions: c.getActions(),
        })
      },
    })
  },

  resetImageSize(ev) {
    var i = ev.currentTarget.dataset.i;
    console.log(i)
    console.log(ev.detail.width)
    if (this.data.customList[i]) {
      console.log(this.data.customList[i])
    }

    if (this.data.customList[i].pHeight == 0) {
      this.data.customList[i].pHeight = ev.detail.width;
    }

    this.setData({
      customList: this.data.customList
    })
  },

  viewMember(ev) {
    wx.setStorage({
      key: 'member_data',
      data: ev.currentTarget.dataset.d,
    })
    wx.navigateTo({
      url: '/pages/memberConsume/memberConsume',
    })
  },

  viewMessage() {
    wx.navigateTo({
      url: '/pages/message/message',
    })
  },

  viewMembers() {
    wx.navigateTo({
      url: '/pages/nearMenber/nearMenber',
    })
  },

  onShow() {
    var _this = this;
    wx.getStorage({
      key: 'C_SHOP_NO',
      success: res => {
        _this.setData({
          C_SHOP_NO: res.data
        })
        this.loadFirstData();
      },
    });

    wx.getStorage({
      key: 'MAIN_C_SHOP_NO',
      success: res => {
        this.getShopList(res.data);
      },
    })
  },

  loadFirstData() {
    wx.getStorage({
      key: 'C_SHOP_NO',
      success: res => {
        this.GetStorInfo();
        this.getShopInfo2();
        this.getMemberList();
        this.getShopData();
        this.getMessageList();
      },
    })
  },

  selectShopData() {
    if (this.data.shopList[this.data.chooseIndex].c_shop_no != this.data.shopInfo.c_shop_no) {
      this.data.C_SHOP_NO = this.data.shopList[this.data.chooseIndex].c_shop_no;
      wx.setStorage({
        key: 'C_SHOP_NO',
        data: this.data.shopList[this.data.chooseIndex].c_shop_no,
      })
        wx.setStorage({
            key: 'shopno',
            data: this.data.shopList[this.data.chooseIndex].c_shop_no,
        })
        app.shopno = this.data.shopList[this.data.chooseIndex].c_shop_no
      this.loadFirstData();
    }
    this.setData({
      showChoose: false,
    })
  },

  chooseShop() {
    this.setData({
      showChoose: true,
    })
  },

  hideDialog() {
    this.setData({
      showChoose: false,
    })
  },

  bindChange(ev) {
    this.setData({
      chooseShopName: this.data.shopList[ev.detail.value[0]].c_name,
    })
    this.data.chooseIndex = ev.detail.value[0]
  },

  getShopList(sn) {
    var str = "ShopNo=" + sn;
    var md5 = util.md5(str);
    var data = {
      bNo: 202,
      ShopNo: sn,
      MD5: md5.toUpperCase()
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        var data = JSON.parse(res.data.replace(/\(|\)/g, ""));
        if (data.code === "100") {
          for (var i = 0; i < data.shopdt.length; i++) {
            if (data.shopdt[i].PARENT_ID === 0) {
              wx.setStorage({
                key: 'MAIN_C_SHOP_NO',
                data: data.shopdt[i].c_shop_no,
              });
            }
          }
          this.setData({
            shopList: data.shopdt,
            chooseShopName: data.shopdt[0].c_name
          })
        }
      }
    })
  },

  GetStorInfo(g) {
    // debugger
    var str = "ShopNo=" + this.data.C_SHOP_NO,
      md5 = util.md5(str),
      _this = this,
      data = {
        bNo: "1703",
        ShopNo: this.data.C_SHOP_NO,
        MD5: md5.toUpperCase()
      };
    wx.request({
      url: config.requestUrl,
      data,
      success(res) {
        var data = JSON.parse(res.data.replace(/\(|\)/g, ""));
        // console.log(data.Result);
        if (data.code === "100") {
          if (data.Result.c_name.length > 16) {
            data.Result.c_name = data.Result.c_name.substr(0, 16) + "..."
          }
          _this.setData({
            shopInfo: data.Result,
          });
          wx.setStorage({
            key: 'shop_data',
            data: data.Result,
          })
        }
        if (g) {
          _this.setData({
            loadtext: "",
          })
          wx.stopPullDownRefresh();
        }
      }
    })
  },

  getShopInfo2(g) {
    var str = "ShopNo=" + this.data.C_SHOP_NO,
      md5 = util.md5(str),
      _this = this,
      data = {
        // bNo: "1704",
        bNo: 1750,
        ShopNo: this.data.C_SHOP_NO,
        MD5: md5.toUpperCase()
      };
    wx.request({
      url: config.requestUrl,
      data,
      success(res) {
        var data = JSON.parse(res.data.replace(/\(|\)/g, ""));
        var data2 = JSON.parse(data.Result);
        // console.log(data2);
        if (data.code === "100") {
          _this.setData({
            srInfo: data2,
          })
          if (data2.zrtb < 0) {
            _this.setData({
              downClass: false
            })
          }
        }
        if (g) {
          wx.stopPullDownRefresh();
        }
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.GetStorInfo("1");
    this.getShopInfo2("1");
    this.getMemberList();
    wx.showLoading({
      title: '',
    });
    setTimeout(function () {
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }, 500);
    this.setData({
      loadtext: "加载中",
    })
  },

  /**
   * 查看最近用户列表
   */
  viewNearMenberList() {
    wx.navigateTo({
      url: '/pages/nearMember/nearMenber',
    })
  },

  scaleTime() {
    // debugger
    var date = new Date();
    var day = date.getDate();
    var dateArr = [];
    var mouth = date.getMonth() + 1;
    if (day - 8 > 0) {
      for (var i = 0; i < 8; i++) {
        day--;
        dateArr.push(mouth + "-" + day);
      }
    } else {
      if (mouth != 3) {
        if (mouth <= 7) {
          if (mouth % 2 === 0) {
            dateArr = this.getDay(mouth, day, 30);
          } else {
            dateArr = this.getDay(mouth, day, 31);
          }
        } else {
          if (mouth % 2 === 0) {
            dateArr = this.getDay(mouth, day, 31);
          } else {
            dateArr = this.getDay(mouth, day, 30);
          }
        }
      } else {
        if (date.getFullYear % 4 === 0) {
          dateArr = this.getDay(mouth, day, 29);
        } else {
          dateArr = this.getDay(mouth, day, 28);
        }
      }
    }
    dateArr.reverse();
    this.setData({
      dateArr,
    })
  },

  getDay(m, day, fullDay) {
    var dateArr = [];
    for (var i = day; i > 0; i--) {
      dateArr.push(m + "-" + i);
    }
    var f = fullDay;
    for (var i = 0; i < 8 - day; i++) {
      if (m === 1) {
        dateArr.push(12 + "-" + (f--));
      } else {
        dateArr.push((m - 1) + "-" + (f--));
      }
    }
    return dateArr;
    data = [{
      income: 25015, // 当天收入
      scale: 32.5, // 收入比例，上升为正，下降为负，
    }, {
      income: 25015, // 当天收入
      scale: -18.4, // 收入比例，上升为正，下降为负，
    }]
  },

  getMemberList() {
    var str = "pageindex&pagesize&ShopNo=" + this.data.pageindex + "*" + 3 + "*" + this.data.C_SHOP_NO;
    // console.log(str)
    var md5 = util.md5(str);
    var data = {
      bNo: 1705,
      pageindex: this.data.pageindex,
      pagesize: 3,
      ShopNo: this.data.C_SHOP_NO,
      MD5: md5.toUpperCase(),
    }

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        if (res.data.code === "100") {
          for (var i = 0; i < res.data.memberList.length; i++) {
            if (res.data.memberList[i]) {
              res.data.memberList[i].pWidth = 0;
              res.data.memberList[i].pHeight = 0;
              res.data.memberList[i].D_OpDate2 = res.data.memberList[i].D_OpDate.substr(0, 16).replace("T", " ");
            }
            if (res.data.memberList[i].wdzpicurllast.indexOf("ovopark") < 0) {
              res.data.memberList[i].wdzpicurllast = this.data.filePath + res.data.memberList[i].wdzpicurllast;
            }
          }
          this.setData({
            // customList: [],
            customList: res.data.memberList,
          })
        } else {
          this.setData({
            customList: [],
          })
        }
      }
    })
  },

})
